package com.runen.wnhz.runen.ui.activity.main;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.runen.wnhz.runen.R;
import com.runen.wnhz.runen.bean.LessonLidBean;
import com.runen.wnhz.runen.bean.LessonPriceChangeBean;
import com.runen.wnhz.runen.bean.OrderInfoBean;
import com.runen.wnhz.runen.bean.OrderSureBean;
import com.runen.wnhz.runen.common.utils.ACacheUtlis;
import com.runen.wnhz.runen.common.utils.NetUtils;
import com.runen.wnhz.runen.common.utils.OkHttpUtils;
import com.runen.wnhz.runen.common.utils.StatusBarCompatUtils;
import com.runen.wnhz.runen.common.utils.ToastUtil;
import com.runen.wnhz.runen.data.entity.ReceivingAddressEntity;
import com.runen.wnhz.runen.di.component.ApplicationComponent;
import com.runen.wnhz.runen.ui.activity.BaseActivity;
import com.runen.wnhz.runen.ui.activity.mine.ReceivingAddressActivity;
import com.runen.wnhz.runen.ui.adapter.puadapter.HelpStudyAdapter;
import com.runen.wnhz.runen.widget.TitleBuilder;

import org.simple.eventbus.Subscriber;

import java.io.IOException;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;

/**
 * Created by Administrator on 2018/6/1 0001.
 */

public class SubmitOrderActivity extends BaseActivity {
    @BindView(R.id.rv_helpstudy)
    RecyclerView mRvHelpStudy;
    HelpStudyAdapter mAdapter;
    private static final int REQUEST_CODE = 1;
    @BindView(R.id.consigneeName)
    TextView consigneeName;
    @BindView(R.id.consigneePhoneNum)
    TextView consigneePhoneNum;
    @BindView(R.id.receivingAddress)
    TextView receivingAddress;
    @BindView(R.id.text_orderBuyTip)
    TextView textOrderBuyTip;
    @BindView(R.id.image_orderPic)
    ImageView imageOrderPic;
    @BindView(R.id.text_orderTitle)
    TextView textOrderTitle;
    @BindView(R.id.text_orderLessonValid)
    TextView textOrderLessonValid;
    @BindView(R.id.text_orderTotalPrice)
    TextView textOrderTotalPrice;
    @BindView(R.id.text_orderCarriage)
    TextView textOrderCarriage;
    @BindView(R.id.text_orderTotalFee)
    TextView textOrderTotalFee;
    @BindView(R.id.text_teachAssistanceLabel)
    TextView textTeachAssistanceLabel;
    @BindView(R.id.text_placeOrder)
    TextView textPlaceOrder;
    @BindView(R.id.linear_root)
    RelativeLayout linearRoot;
    private String token;
    private String lessonLid;
    private String id_str;
    private String aid;
    private String defaultAddress;
    private ReceivingAddressEntity receivingAddressEntity;
    private boolean isFirstStartSubmitOrderActivity = true;
    private boolean isBindingSales = false;
    private double orderTotalFee;
    private PopupWindow payWayWindow;
    private View payWayView;
    private String netDefaultAddress;
    private FormBody formBody;
    private String orderNo;
    private String orderId;
    private String submitTotalFee;


    @Override
    protected int getLayoutView() {
        return R.layout.activity_submitorder;
    }

    @Override
    protected void onTitleClickListen(TitleBuilder.TitleButton clicked) {

    }

    private void interfaceParamJudge() {
        if (id_str != null) {
            if (isFirstStartSubmitOrderActivity) {
                formBody = new FormBody.Builder().add("token", token).add("id", lessonLid).add("id_str", id_str).build();
            } else {
                formBody = new FormBody.Builder().add("token", token).add("id", lessonLid).add("id_str", id_str).add("aid", aid).build();
            }
        } else {
            if (isFirstStartSubmitOrderActivity) {
                formBody = new FormBody.Builder().add("token", token).add("id", lessonLid).build();
            } else {
                formBody = new FormBody.Builder().add("token", token).add("id", lessonLid).add("aid", aid).build();
            }
        }
    }

    private void getOrderDetail() {
        if (token != null && lessonLid != null) {
            interfaceParamJudge();
            Request request = new Request.Builder().url(NetUtils.ORDER_DETAIL).post(formBody).build();
            Call newCall = OkHttpUtils.getOkHttpClient().newCall(request);
            newCall.enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            ToastUtil.showToast("数据请求失败");
                        }
                    });
                }

                @Override
                public void onResponse(Call call, final Response response) throws IOException {
                    handleOrderDeatilData(response);
                }
            });

        }
    }

    private void handleOrderDeatilData(Response response) throws IOException {
        if (response.isSuccessful()) {
            ResponseBody responseBody = response.body();
            if (responseBody != null) {
                String json = responseBody.string();
                final OrderSureBean orderSureBean = new Gson().fromJson(json, OrderSureBean.class);
                if ("1".equals(orderSureBean.getRe())) {
                    final OrderSureBean.DataBean dataBean = orderSureBean.getData();
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            addDataToView(dataBean);
                        }
                    });
                } else if ("0".equals(orderSureBean.getRe())) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            ToastUtil.showToast(orderSureBean.getInfo());
                        }
                    });

                }
            }
        }
    }

    private void addDataToView(OrderSureBean.DataBean dataBean) {
        editor.putBoolean("isFirstStartSubmitOrderActivity", false).commit();
        textOrderBuyTip.setText(dataBean.getTip());
        Glide.with(this).load(dataBean.getPic()).into(imageOrderPic);
        textOrderTitle.setText(dataBean.getTitle());
        textOrderLessonValid.setText("课程有效期:".concat(dataBean.getAging_time()));
        textOrderTotalPrice.setText("￥".concat(dataBean.getTotal_price()));
        textOrderCarriage.setText("￥".concat(dataBean.getEmail_price()));
        orderTotalFee = Double.parseDouble(dataBean.getTotal_fee());
        textOrderTotalFee.setText("金额:￥" + orderTotalFee);
        OrderSureBean.DataBean.AddressListBean address_list = dataBean.getAddress_list();
        editor.putString("net_default_address", new Gson().toJson(address_list)).commit();
        consigneeName.setText(address_list.getConsignee());
        consigneePhoneNum.setText(address_list.getTelephone());
        receivingAddress.setText(address_list.getAddress());
        aid = address_list.getAddress_id();
        if ("1".equals(dataBean.getHave_file())) {
            textTeachAssistanceLabel.setVisibility(View.VISIBLE);
            mRvHelpStudy.setVisibility(View.VISIBLE);
        } else {
            textTeachAssistanceLabel.setVisibility(View.GONE);
            mRvHelpStudy.setVisibility(View.GONE);
        }
        if ("1".equals(dataBean.getIs_file())) {
            isBindingSales = true;
        } else {
            isBindingSales = false;
        }
        mAdapter = new HelpStudyAdapter(this, dataBean.getOtherList(), isBindingSales);
        mRvHelpStudy.setAdapter(mAdapter);
    }

    @Subscriber
    public void onReceiveLessonPriceChangeBeanEvent(LessonPriceChangeBean lessonPriceChangeBean) {
        if (lessonPriceChangeBean != null) {
            if (lessonPriceChangeBean.isPriceRises()) {
                orderTotalFee = orderTotalFee + lessonPriceChangeBean.getPriceChangeVolume();
            } else {
                orderTotalFee = orderTotalFee - lessonPriceChangeBean.getPriceChangeVolume();
            }
            textOrderTotalFee.setText("金额:￥" + orderTotalFee);
        }
    }


    @Override
    protected void initStart() {
        StatusBarCompatUtils.getInstance().TranslucentStatusBar(this, R.color.title_green);
        if (ACacheUtlis.getInstance().getReqeustUser(this) != null) {
            token = ACacheUtlis.getInstance().getReqeustUser(this).getToken();
        }
        payWayView = View.inflate(this, R.layout.pay_way_choose_layout, null);
        payWayWindow = new PopupWindow(payWayView, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        payWayWindow.setOutsideTouchable(true);
        payWayWindow.setTouchable(true);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        linearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        lessonLid = getIntent().getStringExtra("lessonLid");
        id_str = getIntent().getStringExtra("id_str");
        mRvHelpStudy.setLayoutManager(linearLayoutManager);
        defaultAddress = preferences.getString("default_address", null);
        netDefaultAddress = preferences.getString("net_default_address", null);
        receivingAddressEntity = new Gson().fromJson(defaultAddress, ReceivingAddressEntity.class);
        isFirstStartSubmitOrderActivity = preferences.getBoolean("isFirstStartSubmitOrderActivity", true);
        parseData();
        getOrderDetail();
    }

    private void parseData() {
        if (receivingAddressEntity != null) {
            aid = receivingAddressEntity.getAid();
            consigneeName.setText(receivingAddressEntity.getConsignee());
            consigneePhoneNum.setText(receivingAddressEntity.getTelephone());
            receivingAddress.setText(receivingAddressEntity.getProvince() + receivingAddressEntity.getCity() + receivingAddressEntity.getCounty() + receivingAddressEntity.getProvince());
        } else {
            if (netDefaultAddress != null) {
                OrderSureBean.DataBean.AddressListBean addressListBean = new Gson().fromJson(netDefaultAddress, OrderSureBean.DataBean.AddressListBean.class);
                System.out.println("AddressListBean == " + addressListBean.toString());
                aid = addressListBean.getAddress_id();
                consigneeName.setText(addressListBean.getConsignee());
                consigneePhoneNum.setText(addressListBean.getTelephone());
                receivingAddress.setText(addressListBean.getAddress());
            }
        }
    }

    @Override
    public void initToolBar(TitleBuilder mTitleBuilder) {
        mTitleBuilder.setLeftDrawable(R.mipmap.icon_back);
        mTitleBuilder.setMiddleTitleText("提交订单");
        mTitleBuilder.setMiddleTitleTextColor(Color.WHITE);
        mTitleBuilder.setLeftTextOrImageListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
    }

    @OnClick({R.id.linear_receivingAddress, R.id.text_placeOrder})
    public void onClickEvent(View view) {
        Intent intent = new Intent();
        switch (view.getId()) {
            case R.id.linear_receivingAddress:
                intent.setClass(SubmitOrderActivity.this, ReceivingAddressActivity.class);
                intent.putExtra("orderTag", true);
                startActivityForResult(intent, REQUEST_CODE);
                break;
            case R.id.text_placeOrder:
                orderPay();
                break;
        }
    }

    private void orderPay() {
        System.out.println("token == " + token + "  lessonLid == " + lessonLid + "  aid == " + aid + "  id_str == " + id_str);
        if (token != null && lessonLid != null && aid != null) {
            progressDialog.setMessage("正在生成订单信息，请稍等...");
            showProgressDialog();
            if(id_str != null){
                formBody = new FormBody.Builder().add("token",token).add("id",lessonLid).add("id_str",id_str).add("aid",aid).build();
            }else{
                formBody = new FormBody.Builder().add("token",token).add("id",lessonLid).add("aid",aid).build();
            }
            Request request = new Request.Builder().url(NetUtils.ORDER_PAY).post(formBody).build();
            Call newCall = OkHttpUtils.getOkHttpClient().newCall(request);
            newCall.enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            ToastUtil.showToast("数据请求失败");
                            dismissDialog();
                        }
                    });
                }

                @Override
                public void onResponse(Call call, final Response response) throws IOException {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                handleOrderPayData(response);
                            } catch (IOException e) {
                                e.printStackTrace();
                                ToastUtil.showToast("数据请求出现异常");
                                dismissDialog();
                            }
                        }
                    });
                }
            });
        }
    }

    private void handleOrderPayData(Response response) throws IOException {
        if (response.isSuccessful()) {
            ResponseBody responseBody = response.body();
            String json = responseBody.string();
            OrderInfoBean orderInfoBean = new Gson().fromJson(json, OrderInfoBean.class);
            System.out.println("OrderInfoBean == " + orderInfoBean.toString());
            if ("1".equals(orderInfoBean.getRe())) {
                orderId = orderInfoBean.getData().getOrder_id();
                orderNo = orderInfoBean.getData().getOrder_no();
                submitTotalFee = orderInfoBean.getData().getTotal_fee();
                Intent intent = new Intent();
                intent.setClass(SubmitOrderActivity.this, OrderSureActivity.class);
                intent.putExtra("orderNo", orderNo);
                intent.putExtra("orderTotalFee", orderTotalFee);
                startActivity(intent);
            } else if ("0".equals(orderInfoBean.getRe())) {
                ToastUtil.showToast(orderInfoBean.getInfo());
            }
            dismissDialog();
        }

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE && resultCode == Activity.RESULT_OK) {
            ReceivingAddressEntity receivingAddressEntity = (ReceivingAddressEntity) data.getSerializableExtra("address");
            if (receivingAddressEntity != null) {
                String consignee = receivingAddressEntity.getConsignee();
                consigneeName.setText(consignee);
                String telephone = receivingAddressEntity.getTelephone();
                consigneePhoneNum.setText(telephone);
                aid = receivingAddressEntity.getAid();
                String province = receivingAddressEntity.getProvince();
                String city = receivingAddressEntity.getCity();
                String county = receivingAddressEntity.getCounty();
                String place = receivingAddressEntity.getPlace();
                receivingAddress.setText(province.concat(city).concat(county).concat(place));
                getOrderDetail();
            }
        }
    }

    @Override
    public void setupAcitivtyComponent(ApplicationComponent appComponent) {

    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }
}
